/*
chooseStaff  选择弹出框
Author: 朱希望
Syntax: $(element).chooseStaff({
			hiddenName:"dutyAlterationBean.tbStaff.staffId",
			
		});
*/
(function($) {
  $.fn.chooseStaff = function(options) {
	  var defaults = {   
	            target      : "staffdialog",   			//弹出框DIV的ID名字
	            dataType    : "json",		   
	            method      : "post",			   
	            async       : true,   
	            beforeSend  : false,   
	            complete    : false,   
	            error       : false,
	            single      : false,
	            url			: "../../hrm/staff/findStaffByDep.action",	//ajax异步的action
	            hiddenName	: "staff.staffId",			//hidden隐藏域的名字，也是后台接受什么参数的名称
	            hiddenId	: "staffId",				//hidden隐藏域的ID，如果一个页面使用1次以上本插件，必须要设置不同的hiddenId和hiddenName属性
	            ismore		: false,					//为了现实自己的函数
	            title		: "员工选择",				//弹出框上面显示的title
	            changeParam : "depId=",					//异步要传递的参数
	            isNotstaffId: true						//是选择员工ID还是选择用户ID，默认true是选择员工ID，false则是用户ID;
	        };   
	  
	        var options = $.extend(defaults, options); 
	        var resultString="";
	        //把弹出框的DIV和要传到后台的ID隐藏域加上
	        $('body').append("<div id='"+options.target+"' title='"+options.title+"' style='display:none;'> </div>");
	        var target = "#"+options.target;
	        $.ajax({   
	    	    url: '../../system/department/findAllDepName.action',   
	    	    type:'POST',   
	    	    dataType: 'json',   
	    		beforeSend:function(xmlhttprequest){
	    	 	},
	    		success:function(data){
	    	 		
	    	 		var depNameList = data.depNames;
	    	 		if (depNameList != null && depNameList != "undefined" && depNameList.length >0)
	    	 		{
	    	 			resultString+="<tr valign='top' height='35'>"+
    	 				"<td align='left' colspan='3'><span style='font-weight:bold'>部门：</span>"+
    	 				"<select name='depId' class='dep'>"+
	    	 			"<option value='-1'>请选择</option>";
	    	 			for (var i=0;i<depNameList.length;i++) {
	    	 				//alert(depNameList[i][0]);
	    	 					resultString+="<option value='"+depNameList[i][0]+"'>"+depNameList[i][1]+"</option>";
            			}
	    	 			resultString+="</select>"+
	    	 			"</td>"+
	    	 			"</tr>";
	    	 			$(target).find('table').prepend(resultString);
	    	 		}
	    		 },
	    		 error:function(){
	    			alert("出错了！");
	    		 }
	    	 });  
	        //alert(resultString);
	        $(target).append("<table border='0' cellspacing='1' cellpadding='1' width='100%'></table>");
	        $(target).find('table').prepend(
	    	        			"<tr valign='top'>"+
	    	        			"<td valign='middle' width='37%'><select class='allUser' multiple='multiple' size='14' style='width:120px'></select></td>"+
	    	        			"<td valign='middle' width='25%'>"+
	    	        			"<div align='center'>"+
	    	        			"<button type='button' class='btn join' ><span><span>加入&gt;&gt;</span></span></button><br/><br/>"+
	    	        			"<button type='button' class='btn remove' ><span><span>&lt;&lt;移除</span></span></button><br/><br/>"+
	    	        			"<button type='button' class='btn allRemove' ><span><span>全部移除</span></span></button>"+
	    	        			"</div>"+
	    	        			"</td>"+
	    	        			"<td valign='middle' width='37%'>" +
	    	        			"<select class='selectUser' name='selectUser' multiple='multiple' size='14' style='width:120px' ></select>" +
	    	        			"</td>"+
	    	        			"</tr>"+
	    	        			"<tr valign='top'>"+
	        					"<td colspan='3' valign='middle'>"+
	        					"<div align='right'>"+
	        					"<button type='button' class='btn ok'><span><span>确定</span></span></button>&nbsp;&nbsp;"+
	        					"<button type='button' class='btn cancel'><span><span>取消</span></span></button>&nbsp;&nbsp;"+
	        					"</div>"+
	        					"</td>"+
	        					"</tr>");
	       
	    
	      //员工出框开始
	    	$(target).dialog({
	    		bgiframe: true,
	    		autoOpen:false,
	    		resizable :false,
	    		position: 'center',
	    		width: 400,
	    		height: 340,
	    		modal: true
	    	}); 
	        return  $(this).click(function(){   
	        	 var thisa = $(this);
	        	 $(target).dialog('open');
	        	 var id;
	        	 var targetAllUser =$(target).find('.allUser'); 
				 var targetselectUser = $(target).find('.selectUser');
				 var name = "input[name='"+options.hiddenName+"']";
	        	 $(target).find('.dep').bind('change',function(){
	        		//alert($(target).find('.dep').text());
       							  data = function(){
       								targetAllUser.empty();
       								var checkValue=$(target).find('.dep').find('option:selected').val(); 
       								
       								$.ajax({   
       				                    type        : options.method,   
       				                    url         : options.url,   
       				                    dataType    : options.dataType,   
       				                    async       : options.async,   
       				                    data        : options.changeParam+checkValue,   
       				                    beforeSend  : function(){    
       				                                    if(options.beforeSend) options.beforeSend();    
       				                    },   
       				                    complete    : function(XMLHttpReq, textStatus){   
       				                                    if(options.complete) options.complete(XMLHttpReq, textStatus);   
       				                    },   
       				                    success     : function(data){   
       				                    				var optionlist = $(targetselectUser.html());
       				                    				//alert(optionlist.length);
       				                    				$.each(data,function(entryIndex,entry){
       				                    					if(!entry)
       				                    						return 0;  
       				                    					$.each(entry,function(k,v){
       				                    						//alert(v.userId);
       				                    						if(options.isNotstaffId)
       				                    						{
       				                    							id = v.staffId;
       				                    						}
       				                    						else
       				                    						{
       				                    							id=v.userId;
       				                    						}
       				                    						targetAllUser.append("<option value=\"" +id + "\">" + v.name + "</option>");
       				                    						$.each(targetAllUser.find("option"),function(j,p){
       				                    							$.each(optionlist,function(k,o){if(p.value == o.value)$(p).remove();});
       				                    						});
       				                    					});
       				                    				});
       				                    			 if(targetselectUser.find('option').eq(0).val()=='')
	       				             				 {
	       				             					 //alert("aaa");
	       				             					 targetselectUser.find('option').remove();
	       				             				 }
       				                    },   
       				                    error       : function (event, request, settings){    
       				                                    alert("出错了"); 
       				                    }   
       				                }); 
       								 
       							 };
       							data();
       						});
	        	 	var loadadd = function()
	        	 	{
	        	 		if(thisa!=null)
	        	 		{	
	        	 			targetselectUser.empty();
	        	 			var tempArrName = thisa.attr('value').split(",");
	        	 			var tempArrId = $(name).attr('value').split(",");
	        	 			//alert(tempArr[0]);
	        	 			for(var j=0;j<tempArrName.length;j++)
	        	 			{
	        	 				targetselectUser.append("<option value=\"" +tempArrId[j] + "\">" +tempArrName[j] + "</option>");
	        	 			}
	        	 			
	        	 		}
	        	 	};
	        	 	if(thisa!=null)
        	 		{
	        	 		loadadd();
        	 		};
	        	 	
	        	 	var add = function(){
						if (targetAllUser) {
								if(options.single)
								{
									//alert(targetselectUser.find('option').length);
									if(targetselectUser.find('option').length>=1)
									{
										alert("您只能选一个人!");
									}
									else{
										targetselectUser.append(targetAllUser.find('option:selected').removeAttr('selected'));
									}
								}
								else{
									targetselectUser.append(targetAllUser.find('option:selected').removeAttr('selected'));
								}
									
						}
							
					}; 
					var del = function(){
						if (targetselectUser.find('option:selected')) {
							targetAllUser.append(targetselectUser.find('option:selected').removeAttr('selected'));
							targetselectUser.find('option:selected').remove();
						}
					};
					var ok = function(){
						var selectNameList=targetselectUser.find('option');
						var selectName = "";
						selectNameList.each(function(index){
							var a = selectNameList.eq(index).text();
							if(selectName != ""){
								selectName = selectName + ",";
							}
							selectName = selectName + a;
						});

						var optionlist = $(targetselectUser.html());
						var selectId = "";
						var n = optionlist.length;
						for (var i = 0; i < n; i++) {
							if(optionlist[i].value != null&&optionlist[i].value != "null"){
								if (selectId != "") {
									selectId = selectId + ",";
								}
								selectId = selectId + optionlist[i].value;
							}
						}
						thisa.attr("value",selectName);
						$(name).attr("value",selectId);
//						hidePopup();
						$(target).find('.dep').unbind('change');
						$(target).find('.allRemove').unbind('click');
						$(target).dialog("close");
						if(options.ismore)
		                {	var staffId = $('#staffId').val();
		                	//alert("ddd");
		                	 findDepDutyById(staffId);
		                }
					};
					targetAllUser.dblclick(function(){
						add();
					});
					$(target).find('.join').click(function(){
						//alert("aaaa");
						add();
					});
					targetselectUser.dblclick(function(){
						del();
					});
					$(target).find('.remove').click(function(){
						del();
					});
					$(target).find('.allRemove').bind('click',function(){
						targetselectUser.empty();
						data();
					});
					
					$(target).find('.ok').click(function(){
						ok();
					});
					$(target).find('.cancel').click(function(){
						$(target).find('.dep').unbind('change');
						$(target).find('.allRemove').unbind('click');
						$(target).dialog("close");
					});
					//alert("bbbbb");
	                return false;   
	           });    

  }
})(jQuery);
